/**
 * 参数处理工具函数集合
 * 专门用于解决 "For input string: null" 错误
 * 提供统一的参数清理和安全处理方法
 */

import { ElMessage } from "element-plus";

/**
 * 参数清理配置接口
 */
export interface ParamCleanOptions {
  /** 是否启用调试日志 */
  debug?: boolean;
  /** 日志前缀 */
  logPrefix?: string;
  /** 是否保留空字符串 */
  keepEmptyString?: boolean;
  /** 自定义过滤函数 */
  customFilter?: (key: string, value: any) => boolean;
}

/**
 * 检查值是否为"null"相关的无效值
 * @param value 要检查的值
 * @returns 是否为无效值
 */
export function isNullLikeValue(value: any): boolean {
  return (
    value === null ||
    value === undefined ||
    value === "null" ||
    value === "undefined" ||
    (typeof value === 'string' && value.toLowerCase() === 'null') ||
    String(value) === "null"
  );
}

/**
 * 安全的参数清理函数 - 防止"null"字符串传递到后端
 * @param params 原始参数对象
 * @param options 清理配置选项
 * @returns 清理后的参数对象
 */
export function cleanParams(
  params: Record<string, any>,
  options: ParamCleanOptions = {}
): Record<string, any> {
  const {
    debug = false,
    logPrefix = '[ParamUtils]',
    keepEmptyString = false,
    customFilter,
  } = options;

  if (debug) {
    console.log(`${logPrefix} 🔍 开始清理参数:`, {
      原始参数: params,
      参数数量: Object.keys(params || {}).length,
      参数详情: Object.entries(params || {}).map(([key, value]) => ({
        key,
        value,
        type: typeof value,
        isNull: value === null,
        isUndefined: value === undefined,
        isStringNull: value === "null",
        isEmptyString: value === "",
      }))
    });
  }

  const cleanedParams: Record<string, any> = {};
  let filteredCount = 0;

  Object.entries(params || {}).forEach(([key, value]) => {
    // 检查是否为null相关的无效值
    const isNullLike = isNullLikeValue(value);
    
    // 检查是否为空字符串（根据配置决定是否保留）
    const isEmptyStr = !keepEmptyString && value === "";
    
    // 应用自定义过滤器（如果存在）
    const customCheck = customFilter ? customFilter(key, value) : true;

    if (!isNullLike && !isEmptyStr && customCheck) {
      // 安全转换值，确保不会意外产生"null"字符串
      cleanedParams[key] = value === null ? undefined : value;
      
      if (debug) {
        console.log(`${logPrefix} ✅ 保留参数: ${key} = ${value}`);
      }
    } else {
      filteredCount++;
      
      if (debug) {
        console.warn(`${logPrefix} ⚠️ 过滤无效参数: ${key} = ${value} (${typeof value})`);
        console.warn(`${logPrefix} ⚠️ 过滤原因:`, {
          isNullLike,
          isEmptyStr,
          customCheck,
        });
      }
    }
  });

  if (debug) {
    console.log(`${logPrefix} ✅ 参数清理完成:`, {
      原始参数数量: Object.keys(params || {}).length,
      保留参数数量: Object.keys(cleanedParams).length,
      过滤参数数量: filteredCount,
      清理后参数: cleanedParams,
    });
  }

  return cleanedParams;
}

/**
 * 安全的URL参数构造函数
 * @param baseUrl 基础URL
 * @param params 参数对象
 * @param options 清理配置选项
 * @returns 完整的URL字符串
 */
export function buildSafeUrl(
  baseUrl: string,
  params: Record<string, any> = {},
  options: ParamCleanOptions = {}
): string {
  const cleanedParams = cleanParams(params, {
    ...options,
    logPrefix: options.logPrefix || '[SafeUrl]',
  });

  if (Object.keys(cleanedParams).length === 0) {
    return baseUrl;
  }

  const searchParams = new URLSearchParams();
  Object.entries(cleanedParams).forEach(([key, value]) => {
    searchParams.set(key, String(value));
  });

  const queryString = searchParams.toString();
  const separator = baseUrl.includes('?') ? '&' : '?';
  const fullUrl = `${baseUrl}${separator}${queryString}`;

  // 🚨 最终安全检查：确保URL中不包含"null"字符串
  if (fullUrl.includes('null')) {
    console.error(`[SafeUrl] 🚨 警告: 构造的URL中仍包含null字符串!`, {
      baseUrl,
      params,
      cleanedParams,
      fullUrl,
    });
    ElMessage.error('请求参数异常，请刷新页面重试');
  }

  return fullUrl;
}

/**
 * 安全的FormData构造函数
 * @param data 表单数据对象
 * @param options 清理配置选项
 * @returns FormData实例
 */
export function buildSafeFormData(
  data: Record<string, any> = {},
  options: ParamCleanOptions = {}
): FormData {
  const cleanedData = cleanParams(data, {
    ...options,
    logPrefix: options.logPrefix || '[SafeFormData]',
  });

  const formData = new FormData();
  Object.entries(cleanedData).forEach(([key, value]) => {
    // 对于文件类型特殊处理
    if (value instanceof File || value instanceof Blob) {
      formData.append(key, value);
    } else {
      formData.append(key, String(value));
    }
  });

  return formData;
}

/**
 * 批量清理对象数组的参数
 * @param dataList 对象数组
 * @param options 清理配置选项
 * @returns 清理后的对象数组
 */
export function cleanParamsList<T = Record<string, any>>(
  dataList: T[],
  options: ParamCleanOptions = {}
): T[] {
  return dataList.map((item, index) => {
    const cleanedItem = cleanParams(item as any, {
      ...options,
      logPrefix: `${options.logPrefix || '[ParamsList]'}[${index}]`,
    });
    return cleanedItem as T;
  });
}

/**
 * 深度清理嵌套对象的参数
 * @param data 嵌套数据对象
 * @param options 清理配置选项
 * @returns 清理后的数据对象
 */
export function deepCleanParams(
  data: any,
  options: ParamCleanOptions = {}
): any {
  if (Array.isArray(data)) {
    return data.map(item => deepCleanParams(item, options));
  }

  if (data && typeof data === 'object' && data.constructor === Object) {
    const cleaned: any = {};
    Object.entries(data).forEach(([key, value]) => {
      if (!isNullLikeValue(value)) {
        cleaned[key] = deepCleanParams(value, options);
      } else if (options.debug) {
        console.warn(`${options.logPrefix || '[DeepClean]'} ⚠️ 深度过滤无效参数: ${key} = ${value}`);
      }
    });
    return cleaned;
  }

  return isNullLikeValue(data) ? undefined : data;
}

/**
 * API请求前的参数预处理Hook
 * @param params 请求参数
 * @param options 清理配置选项
 * @returns 处理后的参数
 */
export function useApiParams(
  params: Record<string, any>,
  options: ParamCleanOptions = {}
) {
  return cleanParams(params, {
    debug: process.env.NODE_ENV === 'development',
    logPrefix: '[ApiParams]',
    ...options,
  });
}

/**
 * 分页参数安全处理
 * @param pagination 分页对象
 * @returns 安全的分页参数
 */
export function safePaginationParams(pagination: {
  page?: number | null;
  limit?: number | null;
  pageNum?: number | null;
  pageSize?: number | null;
  current?: number | null;
  size?: number | null;
}) {
  return {
    // 标准化分页参数，确保都是有效数字
    ...(pagination.page && pagination.page > 0 ? { pageNum: pagination.page } : { pageNum: 1 }),
    ...(pagination.limit && pagination.limit > 0 ? { pageSize: pagination.limit } : { pageSize: 20 }),
    ...(pagination.current && pagination.current > 0 ? { current: pagination.current } : { current: 1 }),
    ...(pagination.size && pagination.size > 0 ? { size: pagination.size } : { size: 20 }),
  };
}

// 导出常用的参数清理配置
export const PARAM_CLEAN_CONFIGS = {
  /** 开发环境调试配置 */
  DEBUG: {
    debug: true,
    logPrefix: '[Debug]',
    keepEmptyString: false,
  },
  /** 生产环境配置 */
  PRODUCTION: {
    debug: false,
    keepEmptyString: false,
  },
  /** API请求配置 */
  API_REQUEST: {
    debug: process.env.NODE_ENV === 'development',
    logPrefix: '[API]',
    keepEmptyString: false,
  },
  /** 表单提交配置 */
  FORM_SUBMIT: {
    debug: process.env.NODE_ENV === 'development',
    logPrefix: '[Form]',
    keepEmptyString: true, // 表单可能需要保留空字符串
  },
  /** URL构造配置 */
  URL_BUILD: {
    debug: process.env.NODE_ENV === 'development',
    logPrefix: '[URL]',
    keepEmptyString: false,
  },
} as const;
